package com.wisemoresystem.seal.action_rest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.ne.framework.data.util.ChkTools;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.config.Config;
import com.wisemoresystem.seal.model.t_file;
import com.wisemoresystem.seal.util.DateTools;
import com.wisemoresystem.seal.util.file.File64CodeTools;
import com.wisemoresystem.seal.util.file.FileTools;
import com.wisemoresystem.seal.util.json.JsonTools;

@Controller
@Scope("prototype")
public class UploadAction extends ProjBaseAction {

	@RequestMapping("/upload_form")
	public String upload_form() {
		return "/jsp_rest/upload_form";
	}

	@RequestMapping("/test")
	public void upload_form(@RequestParam MultipartFile RemoteFile)
			throws IllegalStateException, IOException {
		upload(RemoteFile);
	}

	// swf 上传
	@RequestMapping("/swfupload")
	public void swfupload(@RequestParam MultipartFile Filedata)
			throws IllegalStateException, IOException {
		upload(Filedata);
	}

	@RequestMapping("/upload")
	public void upload(@RequestParam MultipartFile file)
			throws IllegalStateException, IOException {
		resp.setCharacterEncoding("utf-8");
		String suffix = FileTools.getSuffix(file.getOriginalFilename());
		String filename = System.currentTimeMillis() + "." + suffix;

		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;

		// 保存文件
		t_file tf = new t_file();
		tf.setFile_name(file.getOriginalFilename());
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setFolder_url(folder_url);
		tf.setContent_type(file.getContentType());
		tf.setSize(file.getSize());

		File newFile = new File(Config.DATA_PATH + File.separator + folder
				+ File.separator + tf.getNew_file_name());
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		file.transferTo(newFile);
		oc.saveObj(tf);

		String url = Config.DATA_DOMAIN + "/" + folder_url + "/"
				+ tf.getNew_file_name();

		Map<String, String> end = new HashMap<String, String>();

		// 发送保存结果
		end.put("file_id", tf.get_id());
		end.put("url", url);
		end.put("file_name", tf.getFile_name());
		end.put("content_type", tf.getContent_type());

		System.err.println("上传结果---->" + JsonTools.toJson(end));

		resp.getWriter().print(JsonTools.toJson(end));
		resp.getWriter().flush();
	}

	@RequestMapping("pic")
	@ResponseBody
	public String pic(@RequestBody String json) throws IOException {
		resp.setCharacterEncoding("utf-8");

		Map<String, Object> map = JsonTools.jsonStrToMap(json);
		if (ChkTools.isNull(map)) {

			return "fail";
		}

		String pic = (String) map.get("pic");
		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;
		String filename = System.currentTimeMillis() + ".jpeg";
		// 保存文件
		t_file tf = new t_file();
		tf.setFile_name(filename);
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setFolder_url(folder_url);
		tf.setContent_type("image/jpeg");

		String result = "success";
		if (pic != null) {

			File newFile = new File(Config.DATA_PATH + File.separator + folder
					+ File.separator + tf.getNew_file_name());

			File64CodeTools.writeFiles(newFile, pic);
			oc.saveObj(tf);
			result = tf.get_id();

		} else {
			result = "fail";
		}

		return result;
	}

	@RequestMapping("/download/{file_id}")
	public void download(@PathVariable String file_id) throws Exception {

		resp.setContentType("text/html;charset=utf-8");
		req.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		t_file file = (t_file) oc.findObjById(file_id, t_file.class);

		try {
			String filename = file.getFile_name();

			File f = new File(Config.DATA_PATH + File.separator
					+ file.getFolder(), file.getNew_file_name());
			if (!f.exists()) {
				f = new File(Config.DATA_PATH, "file404.jpg");
				filename = "file404.jpg";
			}

			resp.setContentType("application/x-msdownload;");
			resp.setHeader("Content-disposition", "attachment; filename="
					+ new String(filename.getBytes("utf-8"), "ISO8859-1"));
			resp.setHeader("Content-Length", f.length() + "");

			bis = new BufferedInputStream(new FileInputStream(f));
			bos = new BufferedOutputStream(resp.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}
}
